﻿﻿﻿﻿using DeviceCommons.DataHandling;
using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Models.V1;
using DeviceCommons.Validation;

namespace DeviceCommons.DeviceMessages.Serialization.V1.Parsers
{
    public class DeviceMessageInfoReadingStatesParser : AbstractMessageParser<IDeviceMessageInfoReadingStates>, IDeviceMessageInfoReadingStatesParser
    {
        public DeviceMessageInfoReadingStatesParser() : base(new DeviceMessageInfoReadingStates())
        {
        }

        public override IDeviceMessageInfoReadingStates Parser(ReadOnlySpan<byte> bytes)
        {
            if (bytes == null || bytes.Length == 0)
                throw new ArgumentNullException(nameof(bytes));

            IDeviceMessageInfoReadingStates model = new DeviceMessageInfoReadingStates();
            byte stateCount = bytes[0];
            int currentIndex = 1;
            
            // 直接创建正确大小的数组，避免内存池污染问题
            model.StateArray = new IDeviceMessageInfoReadingState[stateCount];

            for (var i = 0; i < stateCount; i++)
            {
                byte sid = bytes[currentIndex];
                byte type = bytes[currentIndex + 1];
                int valueLength = 2 + DeviceMessageUtilities.GetValueLength(bytes, currentIndex + 1);
                byte[] stateData = bytes.Slice(currentIndex, valueLength).ToArray();

                model.StateArray[i] = DeviceMessageSerializerProvider.InfoReadingStateV1Par.Parser(stateData);
                currentIndex += valueLength;

                if (currentIndex > bytes.Length)
                    throw new DeviceMessageValidationException(
                        ValidationErrorType.IncompleteStateData,
                        $"字节数组不包含完整的状态数据，第{i + 1}个状态数据不完整",
                        nameof(bytes),
                        $"可用数据长度: {bytes.Length} 字节",
                        $"已使用: {currentIndex} 字节");
            }

            Model = model;
            return model;
        }
    }
}
